package test;

import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/**
 * @author tongchen
 * @create 2023-02-17 23:30
 */
public class UDPEchoServer {
    //创建socket变量
    private DatagramSocket socket;
    //通过构造方法指定端口号

    public UDPEchoServer(int port) throws SocketException {
        //检查端口号的合法性
        if(port<0||port>65535){
            throw new BindException("端口建议在合法范围内");
        }
        //创建socket
        this.socket=new DatagramSocket(port);
    }
    //启动服务
    public void start() throws IOException {
        //标识运行
        System.out.println("服务端开始启用.......");
        while(true){
            //使用datagrampacket进行数据的接收
            DatagramPacket datagramPacket = new DatagramPacket(new byte[1024], 1024);
            //使用socket接收数据
            socket.receive(datagramPacket);
            //解析接收到的数据
            String request=new String(datagramPacket.getData(), 0, datagramPacket.getData().length, "utf-8");
            //根据数据获取响应数据
            String response=pocess(request);
            //对响应数据进行封装
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),
                    response.getBytes().length,datagramPacket.getSocketAddress());
            //发送响应数据
            socket.send(responsePacket);
            System.out.printf("[%s:%d] request = %s, response = %s\n", datagramPacket.getAddress().toString(),
                    datagramPacket.getPort(), request, response);
        }

    }

    private String pocess(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        //创建端口号
        UDPEchoServer udpEchoServer = new UDPEchoServer(9090);
        udpEchoServer.start();
    }
}
